package com.study.aspect;

import com.google.common.util.concurrent.RateLimiter;
import com.study.anno.RateLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/9/25 22:37
 */
@Aspect
@Component
public class RateLimitAspect {
    /**
     * RateLimiter Cache
     * different interfaces have different rate limiters
     */
    private ConcurrentHashMap<String, RateLimiter> RATE_LIMITER_CACHE = new ConcurrentHashMap<>();

    @Pointcut("@annotation(com.study.anno.RateLimit)")
    public void rateLimit() {
    }

    @Around("rateLimit()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        // rate limiter cache key -> package name + method name (eg:"com.alibaba.comtroller.getUser")
        String key = methodSignature.getDeclaringTypeName() + "." + method.getName();
        RateLimit rateLimit = AnnotationUtils.findAnnotation(method, RateLimit.class);
        if (rateLimit != null) {
            double value = rateLimit.value();
            int timeout = rateLimit.timeout();
            TimeUnit timeUnit = rateLimit.timeUnit();
            if (RATE_LIMITER_CACHE.get(key) == null) {
                synchronized (key) {
                    if (RATE_LIMITER_CACHE.get(key) == null) {
                        RATE_LIMITER_CACHE.put(key, RateLimiter.create(value));
                    }
                }
            }
            RateLimiter rateLimiter = RATE_LIMITER_CACHE.get(key);
            if (rateLimiter == null || !rateLimiter.tryAcquire(timeout, timeUnit)) {
                // Custom processing logic, such as throwing exceptions
                System.out.println(method.getName() + "interface rate limit");
            }
        }
        return point.proceed();
    }
}
